package com.spring.study.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.spring.study.mapper.EmpMapper;
import com.spring.study.mapper.GoodMapper;
import com.spring.study.mapper.OrderMapper;
import com.spring.study.pojo.Emp;
import com.spring.study.pojo.Good;
import com.spring.study.pojo.Order;
import com.spring.study.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;


@Service
public class EmpServiceImpl implements EmpService {

    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private GoodMapper goodMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public PageInfo<Emp> findAllEmp(Integer page, Integer size) {
        PageHelper.startPage(page,size);
        List<Emp> empList = empMapper.findAllEmp();
        PageInfo<Emp> pageInfo = new PageInfo<>(empList);
        return pageInfo;
    }

    @Override
    public Emp findById(Integer empId) {
        Emp emp = empMapper.selectByPrimaryKey(Long.valueOf(empId));
        return emp;
    }

    @Override
    public int insertEmp(Emp emp) {
        return empMapper.insert(emp);
    }

    @Override
    //购买商品，测试事务
    public void buyGood(Integer empId, Integer goodId,Integer num) {
        Good good = goodMapper.selectByPrimaryKey(Long.valueOf(goodId));
        Integer salary = empMapper.selectByPrimaryKey(Long.valueOf(empId)).getSalary();
        Integer new_salary= (int) (salary-num*good.getPrice());

        goodMapper.updateByPrimaryKeySelective(new Good(goodId,null,null,null,good.getTotals()-num,null,null));
//        int i = 10/0;
        File file = new File("demo.jm");
        System.out.println(file);
        empMapper.updateByPrimaryKeySelective(new Emp(empId, null,new_salary,null,null,null));

        orderMapper.insert(new Order(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")),empId,goodId,num,1,new Date()));

    }
}
